<template>
  <div class="container">
    <!-- 项目用例表格 -->
    <div v-loading="loading">
      <div class="test-add-btn" v-if="isAddTestCase == 1">
        <el-button type="primary" size="default" @click="handleAddCases">导入项目用例</el-button>
      </div>
      <el-table ref="projectCaseRef" stripe :data="filterTableData" row-key="ID" @selection-change="handleSelectionChange">
        <el-table-column v-if="isAddTestCase == 1" type="selection" fixed :selectable="selectable" width="30" align="center"></el-table-column>
        <el-table-column type="expand" fixed width="30">
          <template #default="props">
            <el-descriptions
              class="margin-top"
              title="用例详情："
              :column="6"
              size="small"
            >
              <el-descriptions-item label="项目名称：" :span="1">{{ props.row.pname}}</el-descriptions-item>
              <el-descriptions-item label="用例名称：" align="left" :span="4">{{ props.row.testCaseName}}</el-descriptions-item>
              <el-descriptions-item label="用例编写人：" :span="1">{{ props.row.caseEditMembers}}</el-descriptions-item>

              <el-descriptions-item label="项目分支名称：" :span="2">{{ props.row.pNameBranch}}</el-descriptions-item>
              <el-descriptions-item label="功能模块：" :span="2">{{ props.row.funcModules}}</el-descriptions-item>
              <el-descriptions-item label="二级功能模块：" :span="2">{{ props.row.funcModulesChild}}</el-descriptions-item>
              
              <el-descriptions-item label="前置条件：" :span="3">{{ props.row.beforeConditions}}</el-descriptions-item>
              <el-descriptions-item label="用例优先级：" :span="3">{{ props.row.testCasePriority}}</el-descriptions-item>

              <el-descriptions-item label="操作步骤：" :span="6">
                <el-input v-if="props.row.operationSteps" type="textarea" v-model="props.row.operationSteps" disabled :autosize="true"></el-input>
              </el-descriptions-item>

              <el-descriptions-item label="预期结果：" :span="6">
                <el-input v-if="props.row.expectedResult" type="textarea" v-model="props.row.expectedResult" disabled :autosize="true"></el-input>
              </el-descriptions-item>

              <el-descriptions-item label="实际结果：" :span="6">
                <el-input v-if="props.row.realResult" type="textarea" v-model="props.row.realResult" disabled :autosize="true"></el-input>
              </el-descriptions-item>

              <el-descriptions-item label="备注：" :span="6">
                <el-input v-if="props.row.testCaseRemarks" type="textarea" v-model="props.row.testCaseRemarks" disabled :autosize="true"></el-input>
              </el-descriptions-item>
            </el-descriptions>
          </template>
        </el-table-column>
        <!-- <el-table-column  prop="ID" label="用例ID" width="100" align="center" sortable></el-table-column> -->
        <!-- <el-table-column label="编写人" width="120" align="center">
          <template #="{ row }">
            <el-text :style="{ color: row.caseEditMembers ? '#606266' : '#ccc' }">{{ row.caseEditMembers !== '' ?
              row.caseEditMembers : '—' }}</el-text>
          </template>
        </el-table-column> -->
        <el-table-column label="项目分支" min-width="160" align="center">
          <template #="{ row }">
            <el-text :style="{ color: row.pNameBranch ? '#606266' : '#ccc' }">{{ row.pNameBranch ? row.pNameBranch : '—'
              }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="功能模块" width="240" align="center">
          <template #="{ row }">
            <el-text :style="{ color: row.funcModules ? '#606266' : '#ccc' }">{{ row.funcModules ? row.funcModules : '—'
              }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="二级功能模块" min-width="240" align="center">
          <template #="{ row }">
            <el-text :style="{ color: row.funcModulesChild ? '#606266' : '#ccc' }">{{ row.funcModulesChild ?
              row.funcModulesChild : '—' }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="用例名称" min-width="240" align="left">
          <template #="{ row }">
            <el-text :style="{ color: row.testCaseName ? '#606266' : '#ccc' }">{{ row.testCaseName ? row.testCaseName :
              '—' }}</el-text>
          </template>
        </el-table-column>
        <el-table-column v-if="isAddTestCase == 2"prop="testCasePriority" label="优先级" width="160" align="center"  show-overflow-tooltip></el-table-column>
        <el-table-column v-if="isAddTestCase == 1" prop="testCasePriority" label="优先级" width="160" align="center"  show-overflow-tooltip>
          <template #header>
            <el-input v-model="search" size="small" placeholder="搜索" :prefix-icon="Search" />
          </template>
        </el-table-column>


        <!-- <el-table-column align="right"  width="120" fixed="right">
          <template #header>
            <el-input v-model="search" size="small" placeholder="搜索" :prefix-icon="Search" />
          </template>
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)" :icon="Edit"></el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)" :icon="Delete"></el-button>
          </template>
        </el-table-column> -->
      </el-table>
    </div>
  </div>
</template>

<script setup lang='ts'>
import { ref, reactive, PropType, onMounted, watch, computed, } from 'vue';
import { Delete, Edit, Search } from '@element-plus/icons-vue'
import { GetByIdItemCase, PostRequirementTestCases } from "@/api/newDemands/index";
import { ElMessage } from 'element-plus';


const emit = defineEmits(['add-case-success']);
const props = defineProps({
  itemItemId: {
    type: Number as PropType<any>,
    required: true,
  },
  childId: {
    type: Number as PropType<any>,
    required: true,
  },
  isAddTestCase: {
    type: Number,
    required: true,
  }
});

const loading = ref(false);
const isItemItemId = ref<any>(null);
const isChildId = ref<any>(null);
const isAddTestCase = ref<any>(1);// 1：添加项目用例，2：查看项目用例
const requirementCaseList = ref<any>([]);// 所有项目测试用例
const checkRequirementCases = ref([]);// 选中项目用例数据
const search = ref('')
const filterTableData = computed(() =>
  requirementCaseList.value.filter(
      (data: any) =>
        !search.value ||
        data.testCaseName.toLowerCase().includes(search.value.toLowerCase()) ||
        data.caseEditMembers.toLowerCase().includes(search.value.toLowerCase()) ||
        data.caseEditMembers.toLowerCase().includes(search.value.toLowerCase()) ||
        data.funcModules.toLowerCase().includes(search.value.toLowerCase()) ||
        data.funcModulesChild.toLowerCase().includes(search.value.toLowerCase()) ||
        data.testCasePriority.toLowerCase().includes(search.value.toLowerCase())
    )
);


// 监听 itemItemId
watch(() => props.itemItemId, async (newData) => {
  if (newData) {
    isItemItemId.value = newData;
  }
}, { immediate: true });

// 监听 childId
watch(() => props.childId, async (newData) => {
  if (newData) {
    isChildId.value = newData;
  }
}, { immediate: true });

// 监听 isAddTestCase
watch(() => props.isAddTestCase, async (newOpera) => {
  if (newOpera) {
    isAddTestCase.value = newOpera;
  }
}, { immediate: true });


// TODO 获取所有项目测试用例
const getRequirementCaseList = async () => {
  loading.value = true;
  const { data } = await GetByIdItemCase(isItemItemId.value);
  if (data.code === 200) {
    requirementCaseList.value = data.data;
    loading.value = false;
  } else {
    ElMessage.error(data.msg);
    loading.value = false;
    throw console.error(data.msg);
  };
  loading.value = false;
};


const selectable = (row: any) => ![0].includes(row.ID);

// TODO 多选待添加项目用例到测试任务
const handleSelectionChange = (val: any) => {
  checkRequirementCases.value = val.map(((item: any) => item.ID));
};



// 清空导入/上传测试用例提交数据
const handleRemoveData = async () => {
  search.value = '';
};

// TODO 提交选中项目用例
const handleAddCases = async () => {
  const addTestCaseForm = {
    requirementChildId: isChildId.value,
    filePath: "",
    childCaseList: checkRequirementCases.value
  };

  const { data } = await PostRequirementTestCases(addTestCaseForm);
  if (data.code === 200) {
    handleRemoveData();
    emit("add-case-success", true);
  } else {
    ElMessage.error(data.msg);
    emit('add-case-success', false);
    throw console.error(data.msg);
  }

};

onMounted(async () => {
  await getRequirementCaseList();
})

</script>
<style lang='scss' scoped>
.container {
  width: 100%;
  height: 100%;
  max-height: 70vh;
  overflow: hidden;

  .test-add-btn {
    width: 100%;
    text-align: right;
    margin-bottom: 5px;
  }

  // 确保表格容器有合适的滚动行为
  :deep(.el-table) {
    max-height: calc(70vh - 60px);
    overflow-y: auto;
  }

  // 固定表格头部
  :deep(.el-table__header-wrapper) {
    position: sticky;
    top: 0;
    z-index: 10;
    background: #fff;
  }
}

// .el-descriptions {
//   margin-top: 10px;
// }
.cell-item {
  display: flex;
  align-items: left;
}
.margin-top {
  padding: 10px 20px;
}

</style>